<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="searchWrap">
        <div class="searchBox"><span>状态视角：</span>
          <div @click="selectAll('statusActiveNum')"
               class="searchItem"
               :class="statusActiveNum==='' ? 'active':''">全部({{total?total:'0'}})
          </div>
          <div @click="searchByStatusVersion(item,index)" class="searchItem"
               :class="statusActiveNum === index ? 'active':''" v-for="(item,index) in statusList"
               :key="index">{{ item.title }}  ({{countList.length?formatData(item.title):'0'}})
          </div>
        </div>
        <div class="searchBox"><span>创建视角：</span>
          <div @click="selectAll('roleActiveNum')"
               class="searchItem"
               :class="roleActiveNum==='' ? 'active':''">全部
          </div>
          <div @click="searchByCreate(item,index)" class="searchItem"
               :class="roleActiveNum === index ? 'active':''" v-for="(item,index) in roleList"
               :key="index">{{ item.title }}
          </div>
        </div>
        <div class="searchBox"><span>巡检结果：</span>
          <div @click="selectAll('resultActiveNum')"
               class="searchItem"
               :class="resultActiveNum==='' ? 'active':''">全部
          </div>
          <div @click="searchByResultVersion(item,index)" class="searchItem"
               :class="resultActiveNum === index ? 'active':''" v-for="(item,index) in resultList"
               :key="index">{{ item.title }}
          </div>
        </div>
      </div>
    </el-card>
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" class="ele-form-search" label-width="77px" @keyup.enter.native="reload"
               @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="巡检信息:">
              <el-input v-model="where.number" clearable placeholder="请输巡检任务编号"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="日期范围:">
              <el-date-picker
                style="width: 100%;"
                v-model="date"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button v-if="permission.includes('sys:task:index')" class="ele-btn-icon" icon="el-icon-search"
                         type="primary" @click="reload">
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table ref="table" :columns="columns" :datasource="url" :selection.sync="selection" :where="where"
                     height="calc(100vh - 515px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <div class="btnWrap">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addTask"
                         v-show="permission.includes('sys:task:add')">
                添加
              </el-button>

          </div>
          <div class="btnWrap" v-if="permission.includes('sys:plan:export')">
              <el-button size="small" type="primary" :loading="exportLoading" @click="exportPart" :disabled="!selection.length&&!exportFlag">
                导出
              </el-button>
          </div>
          <div class="btnWrap">
            <el-button size="small" :loading="exportLoading" type="primary"
                       v-if="permission.includes('sys:plan:export')" @click="exportAll">导出全部
            </el-button>
          </div>
        </template>
        <!--工单编号-->
        <template slot="number" slot-scope="{row}">
          <span style="cursor: pointer;color: var(--color-primary)"
                @click="$router.push('/inspection/task/info?id=' + row.id)">
            {{ row.number }}
          </span>
        </template>

        <template slot="acted" slot-scope="{row}">
          <span v-show="row.status==='complete'">{{ row.acted ? '是' : '否' }}</span>
        </template>
        <template slot="exception" slot-scope="{row}">
          <span v-show="row.status==='complete'"  :style="{color:row.exception?'red':''}">{{ row.exception ? '异常' : '正常' }}</span>
        </template>
        <template slot="action" slot-scope="{row}">
          <el-popconfirm class="ele-action" title="确定要删除此巡检任务吗？" @confirm="delInspection(row.id)">
            <el-link v-show="permission.includes('sys:plan:delete')" slot="reference" :underline="false"
                     icon="el-icon-delete" type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

export default {
  computed: {
    ...mapGetters(["permission"])
  },
  data() {
    return {
      total:'',
      exportFlag: false,
      exportLoading: false,
      title: "嘉盛环境工单表格",
      // 表格数据接口
      url: '/pollings',
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          slot: 'number',
          label: '巡检编号',
          width: 200,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          prop: 'customer_name',
          label: '客户',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          prop: 'customer_user_name',
          label: '联系人',
          align: 'center',
          showOverflowTooltip: true,
          width: 100
        },

        {
          prop: 'customer_user_telephone',
          label: '电话',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'customer_address',
          label: '客户地址',
          showOverflowTooltip: true,
          minWidth: 250,
          align: 'center'
        },
        {
          prop: 'plan_at',
          label: '计划时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'user_name',
          label: '负责人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'status_text',
          label: '状态',
          minWidth: 160,
          align: 'center',
        },
        {
          slot: 'acted',
          label: '巡检状态',
          minWidth: 160,
          align: 'center',
        },
        {
          slot: 'exception',
          label: '巡检结果',
          minWidth: 160,
          align: 'center',
        },
        {
          prop: 'complete_at',
          label: '巡检时间',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',

        },
        {
          columnKey: 'action',
          label: '操作',
          width: 150,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: "right"
        }
      ],
      loading: false,
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      //当前编辑的类型
      type: '',
      //客户id
      customer_id: '',
      //客户名字
      customer_name: '',
      roleList: [],
      statusList: [],
      resultList: [],
      //状态搜索激活
      resultActiveNum: '',
      statusActiveNum: '',
      roleActiveNum: '',
      date: [],
      countList:[],
    };
  },
  watch: {},
  mounted() {
    this.getParams()
  },
  methods: {
    addTask(){
      this.$router.push({
        path: '/inspection/task/add',})
    },
    formatData(key){
     return  this.countList.filter((item)=> item.title===key)[0].count
    },
    async getParams(){
     await this.$http.get(`/pollings/params`,).then((res) => {
        this.statusList = res.data.data.status
        this.roleList = res.data.data.role
        this.resultList = res.data.data.result
        return res.data.data.status
      }).then((res) => {
        if (this.$route.query.status) {
          this.statusActiveNum = res.findIndex((item) => item === this.$route.query.status)
          this.where.status = this.$route.query.status
        }
      })
      await this.$http.get(`/pollings/counts`,).then((res) => {
        this.countList = res.data.data
        this.total=res.data.data.filter(item=>item.title==='全部')[0].count
      })
    },
    delInspection(id){
      this.$http.delete(`/pollings/${id}`,).then((res) => {
        if(res.data.code === 0){
          this.$message.success(res.data.msg);
        }else {
          this.$message.error(res.data.msg);
        }
      })
      this.reload()
    },
    startDownload() {
      if (this.selection.length === 0)
        return false
      this.exportFlag = true
    },
    finishDownload() {
      this.exportFlag = false
    },
    /*导出全部*/
    exportAll() {
      this.exportLoading = true
      this.$http.get(`/pollings?export=1`, {params: this.where}).then((res) => {
        this.exportLoading = false
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          //_blank表示在新窗口打开链接
          // link.target = '_blank'
          link.href = res.data.data
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    exportPart() {
      this.exportLoading = true
      this.$http.get(`/pollings?export=1`, {params: {ids:this.selection.map((item)=>{return item.id}).join(',')}}).then((res) => {
        this.exportLoading = false
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          //_blank表示在新窗口打开链接
          // link.target = '_blank'
          link.href = res.data.data
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    //筛选全部
    selectAll(flag) {
      switch (flag) {
        case 'statusActiveNum':
          this.statusActiveNum = ''
          this.where.status = ''
          break;
        case 'roleActiveNum':
          this.roleActiveNum = ''
          this.where.role = ''
          break;
        case 'resultActiveNum':
          this.resultActiveNum = ''
          this.where.result = ''
          break;
      }
      this.reload()
    },
    searchByCreate(item, index) {
      this.roleActiveNum = index
      this.handelCreateSearch(item)
    },
    searchByStatusVersion(item, index) {
      this.statusActiveNum = index
      this.handelStatusSearch(item)
    },
    searchByResultVersion(item, index) {
      this.resultActiveNum = index
      this.handelResultSearch(item)
    },
    handelCreateSearch(item) {
      this.where.role = item.code
      this.reload()
    },
    handelStatusSearch(item) {
      this.where.status = item.code
      this.reload()
    },
    handelResultSearch(item) {
      if(item.code === `1`){
        this.where.result =0
      }else {
        this.where.result =1
      }
      this.reload()
    },
    /* 刷新表格 */
    reload() {
      if (this.date?.length >= 0) {
        this.where.plan_start = this.date[0]
        this.where.plan_end = this.date[1]
      }
      console.log(this.where,33)
      this.$refs.table.reload({where: this.where});
      // this.getStatusNum()

    },
    /* 重置搜索 */
    reset() {
      this.resultActiveNum = ''
      this.statusActiveNum = ''
      this.roleActiveNum = ''
      this.date=[]
      this.where = {};
      this.reload();
    },
  }
}
</script>

<style scoped lang="scss">
.tableTop {
  display: flex;
  justify-content: space-between;
}

.searchWrap {
}

.active {
  background: #dcf3fd;
  border-color: #d0f3f4;
  color: #02aef3 !important;
  padding: 4px 8px;
}

.searchBox {
  display: flex;

  span {
    color: #a7b5b5;
    display: block;
    width: 110px;
    height: 36px;
    font-size: 16px;
  }

  .searchItem {
    border: 1px solid transparent;
    border-radius: 4px;
    color: gray;
    font-size: 13px;
    margin: 0 12px 8px 0;
    max-width: 160px;
    overflow: hidden;
    padding: 4px 8px;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    font-size: 14px;
  }
}

.el-autocomplete {
  width: 100%;

}

.el-input {
  width: 100% !important;
}

.btnWrap {
  display: flex;

  .el-button {
    margin-right: 10px;
  }
}
</style>
